package one.stand.facade;

import com.google.common.collect.Lists;
import one.stand.advice.ResultEnum;
import one.stand.mapper.GoodsMapperExt;
import one.stand.service.GoodsTypeService;
import one.stand.util.AssertUtil;
import one.stand.util.OneListUtil;
import one.stand.util.SqlUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author cjr
 */
@Service
public class GoodsFacadeServiceImpl implements GoodsFacadeService {
    @Autowired
    private GoodsTypeService goodsTypeService;
    @Autowired
    private GoodsMapperExt goodsMapperExt;

    @Override
    @Transactional
    public void removeGoodsTypeWithCheck(Integer goodstypeId) {
        List<Integer> typeIds = goodsTypeService.getChildrenForCheck(goodstypeId);
        if (typeIds == null) { // 子分类
            typeIds = Lists.newArrayList(goodstypeId);
        } else { // 父分类
            if (typeIds.isEmpty()) { // 父分类没有子分类
                goodsTypeService.deleteByIds(Lists.newArrayList(goodstypeId));
            }
        }

        if (OneListUtil.isNotEmpty(typeIds)) {  //子分类校验
            Integer cnt = goodsMapperExt.checkByType(SqlUtil.in(typeIds));
            AssertUtil.isTrue(cnt <= 0, ResultEnum.FAIL, "分类下有产品不允许删除.");
            if (!typeIds.contains(goodstypeId)) {
                typeIds.add(goodstypeId);
            }
            goodsTypeService.deleteByIds(typeIds);
        }
    }
}
